{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JmvzTcYice-_"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zlvAS8a9cD_t"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b2VYQpTttmVN"
      },
      "source": [
        "# TensorFlow Constrained Optimization Example Using CelebA Dataset"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3iFsS2WSeRwe"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/responsible_ai/fairness_indicators/tutorials/Fairness_Indicators_TFCO_CelebA_Case_Study\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/fairness-indicators/blob/master/g3doc/tutorials/Fairness_Indicators_TFCO_CelebA_Case_Study.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/fairness-indicators/tree/master/g3doc/tutorials/Fairness_Indicators_TFCO_CelebA_Case_Study.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/fairness-indicators/g3doc/tutorials/Fairness_Indicators_TFCO_CelebA_Case_Study.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-DQoReGDeN16"
      },
      "source": [
        "This notebook demonstrates an easy way to create and optimize constrained problems using the TFCO library. This method can be useful in improving models when we find that they’re not performing equally well across different slices of our data, which we can identify using [Fairness Indicators](https://www.tensorflow.org/responsible_ai/fairness_indicators/guide). The second of Google’s AI principles states that our technology should avoid creating or reinforcing unfair bias, and we believe this technique can help improve model fairness in some situations. In particular, this notebook will:\n",
        "\n",
        "\n",
        "*   Train a simple, *unconstrained* neural network model to detect a person's smile in images using [`tf.keras`](https://www.tensorflow.org/guide/keras) and the large-scale CelebFaces Attributes ([CelebA](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html)) dataset.\n",
        "*   Evaluate model performance against a commonly used fairness metric across age groups, using Fairness Indicators.\n",
        "*   Set up a simple constrained optimization problem to achieve fairer performance across age groups.\n",
        "*   Retrain the now *constrained* model and evaluate performance again, ensuring that our chosen fairness metric has improved.\n",
        "\n",
        "Last updated: 3/11 Feb 2020"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JyCbEWt5Zxe2"
      },
      "source": [
        "# Installation\n",
        "This notebook was created in [Colaboratory](https://research.google.com/colaboratory/faq.html), connected to the Python 3 Google Compute Engine backend. If you wish to host this notebook in a different environment, then you should not experience any major issues provided you include all the required packages in the cells below.\n",
        "\n",
        "Note that the very first time you run the pip installs, you may be asked to restart the runtime because of preinstalled out of date packages. Once you do so, the correct packages will be used."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "T-Zm-KDdt0bn"
      },
      "outputs": [],
      "source": [
        "#@title Pip installs\n",
        "!pip install -q -U pip==20.2\n",
        "\n",
        "!pip install git+https://github.com/google-research/tensorflow_constrained_optimization\n",
        "!pip install -q tensorflow-datasets tensorflow\n",
        "!pip install fairness-indicators \\\n",
        "  \"absl-py==0.12.0\" \\\n",
        "  \"apache-beam\u003c3,\u003e=2.34\" \\\n",
        "  \"avro-python3==1.9.1\" \\\n",
        "  \"pyzmq==17.0.0\"\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UXWXhBLvISOY"
      },
      "source": [
        "Note that depending on when you run the cell below, you may receive a warning about the default version of TensorFlow in Colab switching to TensorFlow 2.X soon. You can safely ignore that warning as this notebook was designed to be compatible with TensorFlow 1.X and 2.X."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UTBBdSGaZ8aW"
      },
      "outputs": [],
      "source": [
        "#@title Import Modules\n",
        "import os\n",
        "import sys\n",
        "import tempfile\n",
        "import urllib\n",
        "\n",
        "import tensorflow as tf\n",
        
        "from tensorflow import keras\n",
        "\n",
        "import tensorflow_datasets as tfds\n",
        "tfds.disable_progress_bar()\n",
        "\n",
        "import numpy as np\n",
        "\n",
        "import tensorflow_constrained_optimization as tfco\n",
        "\n",
        "from tensorflow_metadata.proto.v0 import schema_pb2\n",
        "from tfx_bsl.tfxio import tensor_adapter\n",
        "from tfx_bsl.tfxio import tf_example_record"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "70tLum8uIZUm"
      },
      "source": [
        "Additionally, we add a few imports that are specific to Fairness Indicators which we will use to evaluate and visualize the model's performance."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "7Se0Z0Bo9K-5"
      },
      "outputs": [],
      "source": [
        "#@title Fairness Indicators related imports\n",
        "import tensorflow_model_analysis as tfma\n",
        "import fairness_indicators as fi\n",
        "from google.protobuf import text_format\n",
        "import apache_beam as beam"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xSG2HP7goGrj"
      },
      "source": [
        "Although TFCO is compatible with eager and graph execution, this notebook assumes that eager execution is enabled by default as it is in TensorFlow 2.x. To ensure that nothing breaks, eager execution will be enabled in the cell below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "W0ZusW1-lBao"
      },
      "outputs": [],
      "source": [
        "#@title Enable Eager Execution and Print Versions\n",
        "if tf.__version__ \u003c \"2.0.0\":\n",
        "  tf.compat.v1.enable_eager_execution()\n",
        "  print(\"Eager execution enabled.\")\n",
        "else:\n",
        "  print(\"Eager execution enabled by default.\")\n",
        "\n",
        "print(\"TensorFlow \" + tf.__version__)\n",
        "print(\"TFMA \" + tfma.VERSION_STRING)\n",
        "print(\"TFDS \" + tfds.version.__version__)\n",
        "print(\"FI \" + fi.version.__version__)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "idY3Uuk3yvty"
      },
      "source": [
        "# CelebA Dataset\n",
        "[CelebA](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) is a large-scale face attributes dataset with more than 200,000 celebrity images, each with 40 attribute annotations (such as hair type, fashion accessories, facial features, etc.) and 5 landmark locations (eyes, mouth and nose positions). For more details take a look at [the paper](https://liuziwei7.github.io/projects/FaceAttributes.html).\n",
        "With the permission of the owners, we have stored this dataset on Google Cloud Storage and mostly access it via [TensorFlow Datasets(`tfds`)](https://www.tensorflow.org/datasets).\n",
        "\n",
        "In this notebook:\n",
        "* Our model will attempt to classify whether the subject of the image is smiling, as represented by the \"Smiling\" attribute\u003csup\u003e*\u003c/sup\u003e.\n",
        "*   Images will be resized from 218x178 to 28x28 to reduce the execution time and memory when training.\n",
        "*   Our model's performance will be evaluated across age groups, using the binary \"Young\" attribute. We will call this \"age group\" in this notebook.\n",
        "\n",
        "___\n",
        "\n",
        "\u003csup\u003e*\u003c/sup\u003e While there is little information available about the labeling methodology for this dataset, we will assume that the \"Smiling\" attribute was determined by a pleased, kind, or amused expression on the subject's face. For the purpose of this case study, we will take these labels as ground truth.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zCSemFST0b89"
      },
      "outputs": [],
      "source": [
        "gcs_base_dir = \"gs://celeb_a_dataset/\"\n",
        "celeb_a_builder = tfds.builder(\"celeb_a\", data_dir=gcs_base_dir, version='2.0.0')\n",
        "\n",
        "celeb_a_builder.download_and_prepare()\n",
        "\n",
        "num_test_shards_dict = {'0.3.0': 4, '2.0.0': 2} # Used because we download the test dataset separately\n",
        "version = str(celeb_a_builder.info.version)\n",
        "print('Celeb_A dataset version: %s' % version)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "Ocqv3R06APfW"
      },
      "outputs": [],
      "source": [
        "#@title Test dataset helper functions\n",
        "local_root = tempfile.mkdtemp(prefix='test-data')\n",
        "def local_test_filename_base():\n",
        "  return local_root\n",
        "\n",
        "def local_test_file_full_prefix():\n",
        "  return os.path.join(local_test_filename_base(), \"celeb_a-test.tfrecord\")\n",
        "\n",
        "def copy_test_files_to_local():\n",
        "  filename_base = local_test_file_full_prefix()\n",
        "  num_test_shards = num_test_shards_dict[version]\n",
        "  for shard in range(num_test_shards):\n",
        "    url = \"https://storage.googleapis.com/celeb_a_dataset/celeb_a/%s/celeb_a-test.tfrecord-0000%s-of-0000%s\" % (version, shard, num_test_shards)\n",
        "    filename = \"%s-0000%s-of-0000%s\" % (filename_base, shard, num_test_shards)\n",
        "    res = urllib.request.urlretrieve(url, filename)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "u5PDLXZb_uIj"
      },
      "source": [
        "## Caveats\n",
        "Before moving forward, there are several considerations to keep in mind in using CelebA:\n",
        "*   Although in principle this notebook could use any dataset of face images, CelebA was chosen because it contains public domain images of public figures.\n",
        "*   All of the attribute annotations in CelebA are operationalized as binary categories. For example, the \"Young\" attribute (as determined by the dataset labelers) is denoted as either present or absent in the image.\n",
        "*   CelebA's categorizations do not reflect real human diversity of attributes.\n",
        "*   For the purposes of this notebook, the feature containing the \"Young\" attribute is referred to as \"age group\", where the presence of the \"Young\" attribute in an image is labeled as a member of the \"Young\" age group and the absence of the \"Young\" attribute is labeled as a member of the \"Not Young\" age group. These are assumptions made as this information is not mentioned in the [original paper](http://openaccess.thecvf.com/content_iccv_2015/html/Liu_Deep_Learning_Face_ICCV_2015_paper.html).\n",
        "*   As such, performance in the models trained in this notebook is tied to the ways the attributes have been operationalized and annotated by the authors of CelebA.\n",
        "*   This model should not be used for commercial purposes as that would violate [CelebA's non-commercial research agreement](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Elkiu92cY2bY"
      },
      "source": [
        "# Setting Up Input Functions\n",
        "The subsequent cells will help streamline the input pipeline as well as visualize performance.\n",
        "\n",
        "First we define some data-related variables and define a requisite preprocessing function."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gDdarTZxk6y4"
      },
      "outputs": [],
      "source": [
        "#@title Define Variables\n",
        "ATTR_KEY = \"attributes\"\n",
        "IMAGE_KEY = \"image\"\n",
        "LABEL_KEY = \"Smiling\"\n",
        "GROUP_KEY = \"Young\"\n",
        "IMAGE_SIZE = 28"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "SD-H70Je0cTp"
      },
      "outputs": [],
      "source": [
        "#@title Define Preprocessing Functions\n",
        "def preprocess_input_dict(feat_dict):\n",
        "  # Separate out the image and target variable from the feature dictionary.\n",
        "  image = feat_dict[IMAGE_KEY]\n",
        "  label = feat_dict[ATTR_KEY][LABEL_KEY]\n",
        "  group = feat_dict[ATTR_KEY][GROUP_KEY]\n",
        "\n",
        "  # Resize and normalize image.\n",
        "  image = tf.cast(image, tf.float32)\n",
        "  image = tf.image.resize(image, [IMAGE_SIZE, IMAGE_SIZE])\n",
        "  image /= 255.0\n",
        "\n",
        "  # Cast label and group to float32.\n",
        "  label = tf.cast(label, tf.float32)\n",
        "  group = tf.cast(group, tf.float32)\n",
        "\n",
        "  feat_dict[IMAGE_KEY] = image\n",
        "  feat_dict[ATTR_KEY][LABEL_KEY] = label\n",
        "  feat_dict[ATTR_KEY][GROUP_KEY] = group\n",
        "\n",
        "  return feat_dict\n",
        "\n",
        "get_image_and_label = lambda feat_dict: (feat_dict[IMAGE_KEY], feat_dict[ATTR_KEY][LABEL_KEY])\n",
        "get_image_label_and_group = lambda feat_dict: (feat_dict[IMAGE_KEY], feat_dict[ATTR_KEY][LABEL_KEY], feat_dict[ATTR_KEY][GROUP_KEY])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iwg3sPmExciD"
      },
      "source": [
        "Then, we build out the data functions we need in the rest of the colab."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KbR64r0VVG5h"
      },
      "outputs": [],
      "source": [
        "# Train data returning either 2 or 3 elements (the third element being the group)\n",
        "def celeb_a_train_data_wo_group(batch_size):\n",
        "  celeb_a_train_data = celeb_a_builder.as_dataset(split='train').shuffle(1024).repeat().batch(batch_size).map(preprocess_input_dict)\n",
        "  return celeb_a_train_data.map(get_image_and_label)\n",
        "def celeb_a_train_data_w_group(batch_size):\n",
        "  celeb_a_train_data = celeb_a_builder.as_dataset(split='train').shuffle(1024).repeat().batch(batch_size).map(preprocess_input_dict)\n",
        "  return celeb_a_train_data.map(get_image_label_and_group)\n",
        "\n",
        "# Test data for the overall evaluation\n",
        "celeb_a_test_data = celeb_a_builder.as_dataset(split='test').batch(1).map(preprocess_input_dict).map(get_image_label_and_group)\n",
        "# Copy test data locally to be able to read it into tfma\n",
        "copy_test_files_to_local()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NXO3woTxiCk0"
      },
      "source": [
        "# Build a simple DNN Model\n",
        "Because this notebook focuses on TFCO, we will assemble a simple, unconstrained `tf.keras.Sequential` model.\n",
        "\n",
        "We may be able to greatly improve model performance by adding some complexity (e.g., more densely-connected layers, exploring different activation functions, increasing image size), but that may distract from the goal of demonstrating how easy it is to apply the TFCO library when working with Keras. For that reason, the model will be kept simple — but feel encouraged to explore this space."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RNZhN_zU8DRD"
      },
      "outputs": [],
      "source": [
        "def create_model():\n",
        "  # For this notebook, accuracy will be used to evaluate performance.\n",
        "  METRICS = [\n",
        "    tf.keras.metrics.BinaryAccuracy(name='accuracy')\n",
        "  ]\n",
        "\n",
        "  # The model consists of:\n",
        "  # 1. An input layer that represents the 28x28x3 image flatten.\n",
        "  # 2. A fully connected layer with 64 units activated by a ReLU function.\n",
        "  # 3. A single-unit readout layer to output real-scores instead of probabilities.\n",
        "  model = keras.Sequential([\n",
        "      keras.layers.Flatten(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), name='image'),\n",
        "      keras.layers.Dense(64, activation='relu'),\n",
        "      keras.layers.Dense(1, activation=None)\n",
        "  ])\n",
        "\n",
        "  # TFCO by default uses hinge loss — and that will also be used in the model.\n",
        "  model.compile(\n",
        "      optimizer=tf.keras.optimizers.Adam(0.001),\n",
        "      loss='hinge',\n",
        "      metrics=METRICS)\n",
        "  return model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7A4uKPNVzPVO"
      },
      "source": [
        "We also define a function to set seeds to ensure reproducible results. Note that this colab is meant as an educational tool and does not have the stability of a finely tuned production pipeline. Running without setting a seed may lead to varied results. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-IVw4EgKzqSF"
      },
      "outputs": [],
      "source": [
        "def set_seeds():\n",
        "  np.random.seed(121212)\n",
        "  tf.compat.v1.set_random_seed(212121)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Xrbjmmeom8pA"
      },
      "source": [
        "# Fairness Indicators Helper Functions\n",
        "Before training our model, we define a number of helper functions that will allow us to evaluate the model's performance via Fairness Indicators.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1EPF_k620CRN"
      },
      "source": [
        "First, we create a helper function to save our model once we train it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ejHbhLW5epar"
      },
      "outputs": [],
      "source": [
        "def save_model(model, subdir):\n",
        "  base_dir = tempfile.mkdtemp(prefix='saved_models')\n",
        "  model_location = os.path.join(base_dir, subdir)\n",
        "  model.save(model_location, save_format='tf')\n",
        "  return model_location"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "erhKEvqByCNj"
      },
      "source": [
        "Next, we define functions used to preprocess the data in order to correctly pass it through to TFMA."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "D2qa8Okwj_U3"
      },
      "outputs": [],
      "source": [
        "#@title Data Preprocessing functions for \n",
        "def tfds_filepattern_for_split(dataset_name, split):\n",
        "  return f\"{local_test_file_full_prefix()}*\"\n",
        "\n",
        "class PreprocessCelebA(object):\n",
        "  \"\"\"Class that deserializes, decodes and applies additional preprocessing for CelebA input.\"\"\"\n",
        "  def __init__(self, dataset_name):\n",
        "    builder = tfds.builder(dataset_name)\n",
        "    self.features = builder.info.features\n",
        "    example_specs = self.features.get_serialized_info()\n",
        "    self.parser = tfds.core.example_parser.ExampleParser(example_specs)\n",
        "\n",
        "  def __call__(self, serialized_example):\n",
        "    # Deserialize\n",
        "    deserialized_example = self.parser.parse_example(serialized_example)\n",
        "    # Decode\n",
        "    decoded_example = self.features.decode_example(deserialized_example)\n",
        "    # Additional preprocessing\n",
        "    image = decoded_example[IMAGE_KEY]\n",
        "    label = decoded_example[ATTR_KEY][LABEL_KEY]\n",
        "    # Resize and scale image.\n",
        "    image = tf.cast(image, tf.float32)\n",
        "    image = tf.image.resize(image, [IMAGE_SIZE, IMAGE_SIZE])\n",
        "    image /= 255.0\n",
        "    image = tf.reshape(image, [-1])\n",
        "    # Cast label and group to float32.\n",
        "    label = tf.cast(label, tf.float32)\n",
        "\n",
        "    group = decoded_example[ATTR_KEY][GROUP_KEY]\n",
        "    \n",
        "    output = tf.train.Example()\n",
        "    output.features.feature[IMAGE_KEY].float_list.value.extend(image.numpy().tolist())\n",
        "    output.features.feature[LABEL_KEY].float_list.value.append(label.numpy())\n",
        "    output.features.feature[GROUP_KEY].bytes_list.value.append(b\"Young\" if group.numpy() else b'Not Young')\n",
        "    return output.SerializeToString()\n",
        "\n",
        "def tfds_as_pcollection(beam_pipeline, dataset_name, split):\n",
        "  return (\n",
        "      beam_pipeline\n",
        "   | 'Read records' \u003e\u003e beam.io.ReadFromTFRecord(tfds_filepattern_for_split(dataset_name, split))\n",
        "   | 'Preprocess' \u003e\u003e beam.Map(PreprocessCelebA(dataset_name))\n",
        "  )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fBKvxd2Tz3hK"
      },
      "source": [
        "Finally, we define a function that evaluates the results in TFMA."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "30YduitftaNB"
      },
      "outputs": [],
      "source": [
        "def get_eval_results(model_location, eval_subdir):\n",
        "  base_dir = tempfile.mkdtemp(prefix='saved_eval_results')\n",
        "  tfma_eval_result_path = os.path.join(base_dir, eval_subdir)\n",
        "\n",
        "  eval_config_pbtxt = \"\"\"\n",
        "        model_specs {\n",
        "          label_key: \"%s\"\n",
        "        }\n",
        "        metrics_specs {\n",
        "          metrics {\n",
        "            class_name: \"FairnessIndicators\"\n",
        "            config: '{ \"thresholds\": [0.22, 0.5, 0.75] }'\n",
        "          }\n",
        "          metrics {\n",
        "            class_name: \"ExampleCount\"\n",
        "          }\n",
        "        }\n",
        "        slicing_specs {}\n",
        "        slicing_specs { feature_keys: \"%s\" }\n",
        "        options {\n",
        "          compute_confidence_intervals { value: False }\n",
        "          disabled_outputs{values: \"analysis\"}\n",
        "        }\n",
        "      \"\"\" % (LABEL_KEY, GROUP_KEY)\n",
        "      \n",
        "  eval_config = text_format.Parse(eval_config_pbtxt, tfma.EvalConfig())\n",
        "\n",
        "  eval_shared_model = tfma.default_eval_shared_model(\n",
        "        eval_saved_model_path=model_location, tags=[tf.saved_model.SERVING])\n",
        "\n",
        "  schema_pbtxt = \"\"\"\n",
        "        tensor_representation_group {\n",
        "          key: \"\"\n",
        "          value {\n",
        "            tensor_representation {\n",
        "              key: \"%s\"\n",
        "              value {\n",
        "                dense_tensor {\n",
        "                  column_name: \"%s\"\n",
        "                  shape {\n",
        "                    dim { size: 28 }\n",
        "                    dim { size: 28 }\n",
        "                    dim { size: 3 }\n",
        "                  }\n",
        "                }\n",
        "              }\n",
        "            }\n",
        "          }\n",
        "        }\n",
        "        feature {\n",
        "          name: \"%s\"\n",
        "          type: FLOAT\n",
        "        }\n",
        "        feature {\n",
        "          name: \"%s\"\n",
        "          type: FLOAT\n",
        "        }\n",
        "        feature {\n",
        "          name: \"%s\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        \"\"\" % (IMAGE_KEY, IMAGE_KEY, IMAGE_KEY, LABEL_KEY, GROUP_KEY)\n",
        "  schema = text_format.Parse(schema_pbtxt, schema_pb2.Schema())\n",
        "  coder = tf_example_record.TFExampleBeamRecord(\n",
        "      physical_format='inmem', schema=schema,\n",
        "      raw_record_column_name=tfma.ARROW_INPUT_COLUMN)\n",
        "  tensor_adapter_config = tensor_adapter.TensorAdapterConfig(\n",
        "    arrow_schema=coder.ArrowSchema(),\n",
        "    tensor_representations=coder.TensorRepresentations())\n",
        "  # Run the fairness evaluation.\n",
        "  with beam.Pipeline() as pipeline:\n",
        "    _ = (\n",
        "          tfds_as_pcollection(pipeline, 'celeb_a', 'test')\n",
        "          | 'ExamplesToRecordBatch' \u003e\u003e coder.BeamSource()\n",
        "          | 'ExtractEvaluateAndWriteResults' \u003e\u003e\n",
        "          tfma.ExtractEvaluateAndWriteResults(\n",
        "              eval_config=eval_config,\n",
        "              eval_shared_model=eval_shared_model,\n",
        "              output_path=tfma_eval_result_path,\n",
        "              tensor_adapter_config=tensor_adapter_config)\n",
        "    )\n",
        "  return tfma.load_eval_result(output_path=tfma_eval_result_path)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "76tZ3vk-tyo9"
      },
      "source": [
        "# Train \u0026 Evaluate Unconstrained Model\n",
        "\n",
        "With the model now defined and the input pipeline in place, we’re now ready to train our model. To cut back on the amount of execution time and memory, we will train the model by slicing the data into small batches with only a few repeated iterations.\n",
        "\n",
        "Note that running this notebook in TensorFlow \u003c 2.0.0 may result in a deprecation warning for `np.where`. Safely ignore this warning as TensorFlow addresses this in 2.X by using `tf.where` in place of `np.where`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3m9OOdU_8GWo"
      },
      "outputs": [],
      "source": [
        "BATCH_SIZE = 32\n",
        "\n",
        "# Set seeds to get reproducible results\n",
        "set_seeds()\n",
        "\n",
        "model_unconstrained = create_model()\n",
        "model_unconstrained.fit(celeb_a_train_data_wo_group(BATCH_SIZE), epochs=5, steps_per_epoch=1000)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nCtBH9DkvtUy"
      },
      "source": [
        "Evaluating the model on the test data should result in a final accuracy score of just over 85%. Not bad for a simple model with no fine tuning."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mgsjbxpTIdZf"
      },
      "outputs": [],
      "source": [
        "print('Overall Results, Unconstrained')\n",
        "celeb_a_test_data = celeb_a_builder.as_dataset(split='test').batch(1).map(preprocess_input_dict).map(get_image_label_and_group)\n",
        "results = model_unconstrained.evaluate(celeb_a_test_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L5jslIrzwIKo"
      },
      "source": [
        "However, performance evaluated across age groups may reveal some shortcomings.\n",
        "\n",
        "To explore this further, we evaluate the model with Fairness Indicators (via TFMA). In particular, we are interested in seeing whether there is a significant gap in performance between \"Young\" and \"Not Young\" categories when evaluated on false positive rate.\n",
        "\n",
        "A false positive error occurs when the model incorrectly predicts the positive class. In this context, a false positive outcome occurs when the ground truth is an image of a celebrity 'Not Smiling' and the model predicts 'Smiling'. By extension, the false positive rate, which is used in the visualization above, is a measure of accuracy for a test. While this is a relatively mundane error to make in this context, false positive errors can sometimes cause more problematic behaviors. For instance, a false positive error in a spam classifier could cause a user to miss an important email."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nFL91nZF1V8D"
      },
      "outputs": [],
      "source": [
        "model_location = save_model(model_unconstrained, 'model_export_unconstrained')\n",
        "eval_results_unconstrained = get_eval_results(model_location, 'eval_results_unconstrained')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "34zHIMW0NHld"
      },
      "source": [
        "As mentioned above, we are concentrating on the false positive rate. The current version of Fairness Indicators (0.1.2) selects false negative rate by default. After running the line below, deselect false_negative_rate and select false_positive_rate to look at the metric we are interested in."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KXMVmUMi0ydk"
      },
      "outputs": [],
      "source": [
        "tfma.addons.fairness.view.widget_view.render_fairness_indicator(eval_results_unconstrained)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zYVpZ-DpBsfD"
      },
      "source": [
        "As the results show above, we do see a **disproportionate gap between \"Young\" and \"Not Young\" categories**.\n",
        "\n",
        "This is where TFCO can help by constraining the false positive rate to be within a more acceptable criterion.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZNnI_Eu70gVp"
      },
      "source": [
        "# Constrained Model Set Up\n",
        "As documented in [TFCO's library](https://github.com/google-research/tensorflow_constrained_optimization/blob/master/README.md), there are several helpers that will make it easier to constrain the problem:\n",
        "\n",
        "1.   `tfco.rate_context()` – This is what will be used in constructing a constraint for each age group category.\n",
        "2.   `tfco.RateMinimizationProblem()`– The rate expression to be minimized here will be the false positive rate subject to age group. In other words, performance now will be evaluated based on the difference between the false positive rates of the age group and that of the overall dataset. For this demonstration, a false positive rate of less than or equal to 5% will be set as the constraint.\n",
        "3.   `tfco.ProxyLagrangianOptimizerV2()` – This is the helper that will actually solve the rate constraint problem.\n",
        "\n",
        "The cell below will call on these helpers to set up model training with the fairness constraint.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BTukzvfD6iWr"
      },
      "outputs": [],
      "source": [
        "# The batch size is needed to create the input, labels and group tensors.\n",
        "# These tensors are initialized with all 0's. They will eventually be assigned\n",
        "# the batch content to them. A large batch size is chosen so that there are\n",
        "# enough number of \"Young\" and \"Not Young\" examples in each batch.\n",
        "set_seeds()\n",
        "model_constrained = create_model()\n",
        "BATCH_SIZE = 32\n",
        "\n",
        "# Create input tensor.\n",
        "input_tensor = tf.Variable(\n",
        "    np.zeros((BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3), dtype=\"float32\"),\n",
        "    name=\"input\")\n",
        "\n",
        "# Create labels and group tensors (assuming both labels and groups are binary).\n",
        "labels_tensor = tf.Variable(\n",
        "    np.zeros(BATCH_SIZE, dtype=\"float32\"), name=\"labels\")\n",
        "groups_tensor = tf.Variable(\n",
        "    np.zeros(BATCH_SIZE, dtype=\"float32\"), name=\"groups\")\n",
        "\n",
        "# Create a function that returns the applied 'model' to the input tensor\n",
        "# and generates constrained predictions.\n",
        "def predictions():\n",
        "  return model_constrained(input_tensor)\n",
        "\n",
        "# Create overall context and subsetted context.\n",
        "# The subsetted context contains subset of examples where group attribute \u003c 1\n",
        "# (i.e. the subset of \"Not Young\" celebrity images).\n",
        "# \"groups_tensor \u003c 1\" is used instead of \"groups_tensor == 0\" as the former\n",
        "# would be a comparison on the tensor value, while the latter would be a\n",
        "# comparison on the Tensor object.\n",
        "context = tfco.rate_context(predictions, labels=lambda:labels_tensor)\n",
        "context_subset = context.subset(lambda:groups_tensor \u003c 1)\n",
        "\n",
        "# Setup list of constraints.\n",
        "# In this notebook, the constraint will just be: FPR to less or equal to 5%.\n",
        "constraints = [tfco.false_positive_rate(context_subset) \u003c= 0.05]\n",
        "\n",
        "# Setup rate minimization problem: minimize overall error rate s.t. constraints.\n",
        "problem = tfco.RateMinimizationProblem(tfco.error_rate(context), constraints)\n",
        "\n",
        "# Create constrained optimizer and obtain train_op.\n",
        "# Separate optimizers are specified for the objective and constraints\n",
        "optimizer = tfco.ProxyLagrangianOptimizerV2(\n",
        "      optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n",
        "      constraint_optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n",
        "      num_constraints=problem.num_constraints)\n",
        "\n",
        "# A list of all trainable variables is also needed to use TFCO.\n",
        "var_list = (model_constrained.trainable_weights + list(problem.trainable_variables) +\n",
        "            optimizer.trainable_variables())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "thEe8A8UYbrO"
      },
      "source": [
        "The model is now set up and ready to be trained with the false positive rate constraint across age group.\n",
        "\n",
        "Now, because the last iteration of the constrained model may not necessarily be the best performing model in terms of the defined constraint, the TFCO library comes equipped with `tfco.find_best_candidate_index()` that can help choose the best iterate out of the ones found after each epoch. Think of `tfco.find_best_candidate_index()` as an added heuristic that ranks each of the outcomes based on accuracy and fairness constraint (in this case, false positive rate across age group) separately with respect to the training data. That way, it can search for a better trade-off between overall accuracy and the fairness constraint.\n",
        "\n",
        "The following cells will start the training with constraints while also finding the best performing model per iteration."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "73doG4HL6nPS"
      },
      "outputs": [],
      "source": [
        "# Obtain train set batches.\n",
        "\n",
        "NUM_ITERATIONS = 100  # Number of training iterations.\n",
        "SKIP_ITERATIONS = 10  # Print training stats once in this many iterations.\n",
        "\n",
        "# Create temp directory for saving snapshots of models.\n",
        "temp_directory = tempfile.mktemp()\n",
        "os.mkdir(temp_directory)\n",
        "\n",
        "# List of objective and constraints across iterations.\n",
        "objective_list = []\n",
        "violations_list = []\n",
        "\n",
        "# Training iterations.\n",
        "iteration_count = 0\n",
        "for (image, label, group) in celeb_a_train_data_w_group(BATCH_SIZE):\n",
        "  # Assign current batch to input, labels and groups tensors.\n",
        "  input_tensor.assign(image)\n",
        "  labels_tensor.assign(label)\n",
        "  groups_tensor.assign(group)\n",
        "\n",
        "  # Run gradient update.\n",
        "  optimizer.minimize(problem, var_list=var_list)\n",
        "\n",
        "  # Record objective and violations.\n",
        "  objective = problem.objective()\n",
        "  violations = problem.constraints()\n",
        "\n",
        "  sys.stdout.write(\n",
        "      \"\\r Iteration %d: Hinge Loss = %.3f, Max. Constraint Violation = %.3f\"\n",
        "      % (iteration_count + 1, objective, max(violations)))\n",
        "\n",
        "  # Snapshot model once in SKIP_ITERATIONS iterations.\n",
        "  if iteration_count % SKIP_ITERATIONS == 0:\n",
        "    objective_list.append(objective)\n",
        "    violations_list.append(violations)\n",
        "\n",
        "    # Save snapshot of model weights.\n",
        "    model_constrained.save_weights(\n",
        "        temp_directory + \"/celeb_a_constrained_\" +\n",
        "        str(iteration_count / SKIP_ITERATIONS) + \".h5\")\n",
        "\n",
        "  iteration_count += 1\n",
        "  if iteration_count \u003e= NUM_ITERATIONS:\n",
        "    break\n",
        "\n",
        "# Choose best model from recorded iterates and load that model.\n",
        "best_index = tfco.find_best_candidate_index(\n",
        "    np.array(objective_list), np.array(violations_list))\n",
        "\n",
        "model_constrained.load_weights(\n",
        "    temp_directory + \"/celeb_a_constrained_\" + str(best_index) + \".0.h5\")\n",
        "\n",
        "# Remove temp directory.\n",
        "os.system(\"rm -r \" + temp_directory)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6r-6_R_gSrsT"
      },
      "source": [
        "After having applied the constraint, we evaluate the results once again using Fairness Indicators."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5G6B3OR9CUmo"
      },
      "outputs": [],
      "source": [
        "model_location = save_model(model_constrained, 'model_export_constrained')\n",
        "eval_result_constrained = get_eval_results(model_location, 'eval_results_constrained')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sVteOnE80ATS"
      },
      "source": [
        "As with the previous time we used Fairness Indicators, deselect false_negative_rate and select false_positive_rate to look at the metric we are interested in.\n",
        "\n",
        "Note that to fairly compare the two versions of our model, it is important to use thresholds that set the overall false positive rate to be roughly equal. This ensures that we are looking at actual change as opposed to just a shift in the model equivalent to simply moving the threshold boundary. In our case, comparing the unconstrained model at 0.5 and the constrained model at 0.22 provides a fair comparison for the models."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GRIjYftvuc7b"
      },
      "outputs": [],
      "source": [
        "eval_results_dict = {\n",
        "    'constrained': eval_result_constrained,\n",
        "    'unconstrained': eval_results_unconstrained,\n",
        "}\n",
        "tfma.addons.fairness.view.widget_view.render_fairness_indicator(multi_eval_results=eval_results_dict)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lrT-7EBrcBvV"
      },
      "source": [
        "With TFCO's ability to express a more complex requirement as a rate constraint, we helped this model achieve a more desirable outcome with little impact to the overall performance. There is, of course, still room for improvement, but at least TFCO was able to find a model that gets close to satisfying the constraint and reduces the disparity between the groups as much as possible."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "Fairness Indicators TFCO CelebA Case Study.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
